<template>
  <el-dialog title="品牌分类关联" width="40%" :close-on-click-modal="false" draggable v-model="visible">
    <div style="margin-bottom: 20px">
      <el-popover :visible="relation.visible" placement="right" width="400" trigger="click">
        <el-form :model="dataForm" :rules="dataRule" ref="dataFormRef" @keyup.enter="dataFormSubmit(dataFormRef)" label-width="80px">
          <el-form-item label="选择分类" prop="categoryId">
            <category-cascader v-model="dataForm.categoryId" ref="cascaderRef" />
          </el-form-item>
          <el-form-item>
            <el-button @click="relation.visible = false">取消</el-button>
            <el-button type="primary" @click="dataFormSubmit(dataFormRef)" :disabled="relation.submitted">确定</el-button>
          </el-form-item>
        </el-form>
        <template #reference>
          <el-button v-if="admin.isAuth('product:brand:relation:save')" type="primary" @click="addCascaderEvent()">新增关联</el-button>
        </template>
      </el-popover>
    </div>
    <el-table :data="table.dataList" height="300px" v-loading.lock="table.loading" element-loading-text="拼命加载中" style="width: 100%">
      <el-table-column type="index" width="50" />
      <el-table-column prop="brandName" label="品牌名" />
      <el-table-column prop="categoryName" label="分类名" />
      <el-table-column fixed="right" header-align="center" align="center" width="100" label="操作">
        <template #default="scope">
          <el-button v-if="admin.isAuth('product:brand:relation:delete')" type="danger" link @click="deleteRelationEvent(scope.row)">移除</el-button>
        </template>
      </el-table-column>
    </el-table>
    <template #footer>
      <div class="ad-footer">
        <el-button @click="visible = false">关闭</el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script lang="ts" setup>
import admin from "@/utils/admin";
import http from "@/utils/httpRequest";
import validate from "@/utils/validate";
import { ElMessageBox, FormInstance } from "element-plus";
import { ref, reactive, nextTick, defineExpose, defineEmits } from "vue";

import CategoryCascader from "../common/category-cascader.vue";

// 弹窗是否显示
const visible = ref(false);

// 表单数据
const dataForm = reactive({
  brandId: undefined,
  categoryId: undefined,
});

// 表格
const table = reactive({
  // 表格数据
  dataList: [],
  // 表格加载状态
  loading: false,
});

// 分类级联选择器
const relation = reactive({
  // 是否显示
  visible: false,
  // 提交按钮是否禁用
  submitted: false,
});

// 表单校验
const dataRule = reactive({
  categoryId: validate.required("分类"),
});

// 分类引用
const cascaderRef = ref();

// 表单引用
const dataFormRef = ref<FormInstance>();

// 品牌-分类数据列表初始化
const initTable = async (node) => {
  dataForm.brandId = node.id;
  visible.value = true;
  await nextTick();
  loadCascaderData();
};

// 加载表格数据
const loadCascaderData = () => {
  table.loading = true;
  http
    .post({
      url: `/product/brand/relation/list`,
      data: {
        brandId: dataForm.brandId,
      },
    }).then(({ data }) => {
      if (http.success(data)) {
        table.dataList = data.body;
      } else {
        table.dataList = [];
      }
      table.loading = false;
    });
};

// 加载分类级联数据
const addCascaderEvent = () => {
  relation.visible = true;
  cascaderRef.value.clearCheckedNodes();
};

// 表单提交
const dataFormSubmit = (form: FormInstance | undefined) => {
  if (relation.submitted) {
    return;
  }
  form.validate((valid) => {
    if (valid) {
      relation.submitted = true;
      http
        .post({
          url: `/product/brand/relation/save`,
          data: {
            brandId: dataForm.brandId,
            categoryId: dataForm.categoryId[dataForm.categoryId.length - 1],
          },
        }).then(({ data }) => {
          if (http.success(data, true, true)) {
            relation.visible = false;
            loadCascaderData();
          }
          relation.submitted = false;
        });
    }
  });
};

// 删除关联关系
const deleteRelationEvent = (node) => {
  ElMessageBox.confirm(`确定要删除分类[${node.categoryName}]的关联关系吗?`, "提示", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  }).then(() => {
    http
      .post({
        url: `/product/brand/relation/delete`,
        data: {
          brandId: dataForm.brandId,
          categoryId: node.categoryId,
        },
      }).then(({ data }) => {
        if (http.success(data, true, true)) {
          loadCascaderData();
        }
      });
  });
};

// 暴露方法
defineExpose({ initTable });
</script>
